/*
 * Copyright (C) 2015 备胎金服
 * 未经授权允许不得进行拷贝和修改
 *   http://www.btjf.com/
 */
package com.zhangman.framework.implementation;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

/**
 * Created by zhangman on 2016/11/1 10:50.
 * Email: zhangman523@126.com
 */
public class AndroidFastRenderView extends SurfaceView implements Runnable {
  AndroidGame mGame;
  Bitmap frameBuffer;
  Thread renderThread = null;
  SurfaceHolder mHolder;
  volatile boolean running = false;

  public AndroidFastRenderView(AndroidGame androidGame, Bitmap frameBuffer) {
    super(androidGame);
    this.mGame = androidGame;
    this.frameBuffer = frameBuffer;
    this.mHolder = getHolder();
  }

  public void resume() {
    running = true;
    renderThread = new Thread(this);
    renderThread.start();
  }

  @Override public void run() {
    Rect dstRect = new Rect();
    long startTime = System.nanoTime();
    while (running) {
      if (!mHolder.getSurface().isValid()) {
        continue;
      }
      float deltaTime = (System.nanoTime() - startTime) / 10000000.000f;
      startTime = System.nanoTime();
      if (deltaTime > 3.15) {
        deltaTime = (float) 3.15;
      }
      mGame.getCurrentScreen().update(deltaTime);
      mGame.getCurrentScreen().pain(deltaTime);

      Canvas canvas = mHolder.lockCanvas();
      canvas.getClipBounds(dstRect);
      canvas.drawBitmap(frameBuffer, null, dstRect, null);
      mHolder.unlockCanvasAndPost(canvas);
    }
  }

  public void pause() {
    running = false;
    while (true) {
      try {
        renderThread.join();
      } catch (InterruptedException e) {
      }
    }
  }
}
